package com.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by lanxiaolong on 2019/1/8.
 */
public class EchoServer {
    private final int port = 9999;

    public static void main(String[] args) throws Exception {
        new EchoServer().start();
    }

    public void start() throws Exception {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        EventLoopGroup group = new NioEventLoopGroup();  // 创建EventLoopGroup
        try {
            ServerBootstrap b = new ServerBootstrap();  // 创建ServerBootstrap
            b.group(group)
                    .channel(NioServerSocketChannel.class)  // 指定所使用的NIO传输Channel
                    .localAddress(new InetSocketAddress(port))
                    // 添加一个EchoServerHandler到子Channel的ChannelPipeline
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            // EchoServerHandler被标注为@Sharable,所以我们总是可以使用同样的实例
                            ch.pipeline().addLast(serverHandler);
                        }
                    });
            ChannelFuture f = b.bind().sync();  // 异步的绑定到服务器，调用sync()方法阻塞等待直到绑定成功
            // 获取channel的closeFuture()，并阻塞当前线程直到它完成
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();  // 关闭EventLoopGroup，并释放所有资源
        }
    }
}
